<?php

/**
 * Created by PhpStorm.
 * User: 孙克强
 * Date: 2018/1/24
 * Time: 8:44
 */
class userRole extends CI_Controller
{
    //数据传输
    public $token_data;
    //主页
    public function index(){$this->load->view('user_role/userRole');}
    /**
     * Role constructor.
     */
    public function __construct(){
        parent::__construct();
        $this->load->model('userRole_model');
        $this->load->model('role_model');
        $userToken = new Usertoken_helper();
        $this->token_data['token'] = $userToken->check_token($this);
        //$this->token_data['user_token'] = $userToken->check_userToken($this);
        $this->token_data['user_token']['flag']=1;
    }

    /**
     * userRoleList接口
     */
    public function imp_index(){
        if($this->token_data['user_token']['flag']){
            //如果访问合法便进行数据操纵
            if($this->token_data['token']['tag']){
                $data = $this->userRole_model->getAll();
                $this->token_data['data'] = $data;
            }
            $json = json_encode($this->token_data['data']);
            echo $json;
        } else {
            echo '0';
        }
    }

    /**
     * 查询所有角色和人员角色表
     */
    public function test(){
        if($this->token_data['user_token']['flag']) {
            if ($this->token_data['token']['tag']) {
                $user_id = $_GET['user_id'];
                $userRoles = $this->userRole_model->getAll($user_id);
                $this->token_data['userRoles'] = $userRoles;
                $roles = $this->role_model->getAll();
                $this->token_data['roles'] = $roles;
            }
            $json = json_encode($this->token_data);
            echo $json;
        }else {
            echo '0';
        }
    }

    /**
     * 修改人员角色接口--修改前删除旧数据
     */
    public function user_role_edit(){
        if($this->token_data['user_token']['flag']) {
            if ($this->token_data['token']['tag']) {
                $user_id = $_POST['user_id'];
                $this->userRole_model->del($user_id);
            }
            $json = json_encode($this->token_data);
            echo $json;
        }else {
            echo '0';
        }
    }

    /**
     * 修改人员角色接口--修改后添加新数据
     */
    public function add_user_role(){
        if($this->token_data['user_token']['flag']) {
            if ($this->token_data['token']['tag']) {
                $data = $_POST['data'];
                $user_id = $_POST['user_id'];
                $arr = json_decode($data, true);
                $this->userRole_model->del($user_id);
                $index = count($arr);
                for ($i = 0; $i < $index;) {
                    $this->userRole_model->addUserRole($user_id, $arr[$i]);
                    $i++;
                }
                $this->token_data['success'] = 1;
            }
            $json = json_encode($this->token_data);
            echo $json;
        }else {
            echo '0';
        }
    }

}